package thread;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2023-11-01
 * Time：14:33
 */
public class Demo6 {
    public static final long Count = 20_0000_0000;
    public static void serial() {
        long begin = System.currentTimeMillis();
        int a = 0;
        for (long i = 0; i < Count; i++) {
            a++;
        }
        a = 0;
        for (long i = 0; i < Count; i++) {
            a++;
        }
        long end = System.currentTimeMillis();
        System.out.println("单线程消耗时间：" + (end-begin) + "ms");
    }

    private static void concurrency() {
        long begin = System.currentTimeMillis();
        Thread t1 = new Thread(() -> {
            int a = 0;
            for (long i = 0; i < Count; i++) {
                a++;
            }
        });
        Thread t2 = new Thread(() -> {
             int a = 0;
            for (long i = 0; i < Count; i++) {
                a++;
            }
        });
        t1.start();
        t2.start();

        //join是等待线程结束 在主线程中调用t1.join，意思是让main线程等待t1执行完
        //这两个join操作谁先谁后不影响
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        long end = System.currentTimeMillis();
        System.out.println("并发执行消耗时间：" + (end-begin) + "ms");
    }

    public static void main(String[] args) {
        //serial();
        concurrency();
    }
}
